
const getElementY = (elem) => {
  return document.querySelector(elem).getBoundingClientRect().top + window.pageYOffset
}

/**
 * 滚动到元素位置
 * @param {String} elem DOM元素
 * @param {Number} duration 动画持续时间
 * @param {Number} offset 偏移量
 */
const scrollToElem = (elem, duration, offset) => {
  const startingY = window.pageYOffset
  const domY = getElementY(elem)
  const diff = domY - startingY + offset
  if (!diff) {
    return
  }
  const easing = (t) => t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1
  let start
  window.requestAnimationFrame(function step (timestamp) {
    if (!start) {
      start = timestamp
    }
    const time = timestamp - start
    // 计算时间差值，根据差值计算偏移量
    let percent = Math.min(time / duration, 1)
    percent = easing(percent)
    window.scrollTo(0, startingY + diff * percent)
    if (time < duration) {
      window.requestAnimationFrame(step)
    }
  })
}

export {
  scrollToElem
}
